package com.bdqn.petmalldemo.controller;


import com.alibaba.fastjson.JSONObject;
import com.bdqn.petmalldemo.common.ReturnResult;
import com.bdqn.petmalldemo.common.TokenCache;
import com.bdqn.petmalldemo.entity.User;
import com.bdqn.petmalldemo.service.CartService;
import com.bdqn.petmalldemo.utils.CommonUtils;
import com.bdqn.petmalldemo.vo.CartProductVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Lenovo
 * @since 2020-02-10
 */
@RestController
@RequestMapping("/cart")
public class CartController {
    @Resource
    private CartService cartService;
    @ApiOperation(value = "添加商品到购物车")
    @PostMapping(value = "/add")
    public ReturnResult addProductToCat(String token,String productId,Integer quantity){
        ReturnResult returnResult = CommonUtils.checkUserLogin(token);
        User user = JSONObject.parseObject(TokenCache.get(token), User.class);
        cartService.addProductToCart(user.getId(),productId,quantity);
        return  returnResult;
    }

    @ApiOperation(value = "查询当前用户的购物车信息")
    @PostMapping(value = "list")
    public ReturnResult getCartList(String token){
        ReturnResult returnResult = CommonUtils.checkUserLogin(token);
        User user = JSONObject.parseObject(TokenCache.get(token), User.class);
        List<CartProductVo> cartProductVoList= cartService.getCartProductByUserId(user.getId());
        return  returnResult.data(cartProductVoList);
    }

    @ApiOperation(value = "删除购物车记录")
    @PostMapping(value = "/delete")
    public ReturnResult deleteCartProductById(String token,Long cartId){
        ReturnResult returnResult = CommonUtils.checkUserLogin(token);
        cartService.removeById(cartId);
        return returnResult;
    }
}

